<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use app\common\model\goods\SpecValue;

/**
 * 商品规格管理
 *
 * @icon fa fa-circle-o
 */
class Spec extends Backend
{
    
    /**
     * Spec模型对象
     * @var \app\common\model\goods\Spec
     */
    protected $model = null;
    protected $spec_value_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\goods\Spec;
        $this->spec_value_model = new SpecValue();
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function addSpec()
    {
        $spec_name = $this->request->request('spec_name');
        $spec_value = $this->request->request('spec_value');

        // 判断规格组是否存在
        if (!$spec_id = $this->model->getSpecIdByName($spec_name)) {
            if ($this->model->add($spec_name) && $this->spec_value_model->add($this->model['spec_id'], $spec_value)) {
                $this->success('', '', [
                    'spec_id' => (int)$this->model['spec_id'],
                    'spec_value_id' => (int)$this->spec_value_model['spec_value_id']
                ]);
            }
            $this->error('Unknown error');
        }

        // 判断规格值是否存在
        if ($spec_value_id = $this->spec_value_model->getSpecValueIdByName($spec_id, $spec_value)) {
            $this->success('', '', [
                'spec_id' => (int)$spec_id,
                'spec_value_id' => (int)$spec_value_id
            ]);
        }

        // 添加规格值
        if ($this->spec_value_model->add($spec_id, $spec_value)) {
            $this->success('', '', [
                'spec_id' => (int)$spec_id,
                'spec_value_id' => (int)$this->spec_value_model['spec_value_id']
            ]);
        }
        $this->error('Unknown error.');
    }

    /**
     * 添加规格值
     * @param $spec_id
     * @param $spec_value
     * @return array
     */
    public function addSpecValue($spec_id, $spec_value)
    {
        // 判断规格值是否存在
        if ($specValueId = $this->spec_value_model->getSpecValueIdByName($spec_id, $spec_value)) {
            $this->success('', '', [
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->spec_value_model->add($spec_id, $spec_value))
            $this->success('', '', [
                'spec_value_id' => (int)$this->spec_value_model['spec_value_id'],
            ]);
        $this->error();
    }
}
